package com.lynn.task;

import com.rabbitmq.client.*;

import java.io.IOException;

import static com.lynn.task.MsgTask.TASK_QUEUE_NAME;

/**
 * @Description: 工作者2
 * @Date: 2019/2/10 11:25
 * @Auther: lynn
 */
public class Work_2 {
    public static void main(String[] args) throws Exception {
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();

        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        System.out.println("Worker2  Waiting for messages");

        //每次从队列获取的数量
        channel.basicQos(1);

        final Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Worker2  Received '" + message + "'");
                try {
                    //判断逻辑异常的时候关闭管道
                    if (message.substring(message.length() - 1).equals("9")) {
                        throw new Exception();
                    }
                    //doWork(message);
                } catch (Exception e) {
                    channel.abort();
                } finally {
                    System.out.println("Worker2 Done");
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        boolean autoAck = false;
        //消息消费完成确认
        channel.basicConsume(TASK_QUEUE_NAME, autoAck, consumer);
    }

    private static void doWork(String task) {
        try {
            Thread.sleep(1000); // 暂停1秒钟
        } catch (InterruptedException _ignored) {
            Thread.currentThread().interrupt();
        }
    }
}
